package org.micro.alibaba.provider.controller;

import org.micro.alibaba.common.domain.Item;
import org.micro.alibaba.common.domain.User;
import org.micro.alibaba.provider.feign.UserFeignClient;
import org.micro.alibaba.provider.service.ItemService;
import org.micro.alibaba.provider.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * @author keven
 * @date 2025-07-03 11:04 上午
 * @Description
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private UserFeignClient userFeignClient;

    @PostMapping("/createOrder")
    public void createOrder(Long userId, Long itemId,Integer num) {
        User user = userFeignClient.getUserById(userId);
        if (null == user) {
            throw new RuntimeException("用户不存在");
        }
        Item item = itemService.findById(itemId);
        if (null == item) {
            throw new RuntimeException("商品不存在");
        }
        Integer itemNum = item.getNum();
        if (num > itemNum) {
            throw new RuntimeException("商品库存不足");
        }
        BigDecimal price = item.getPrice();
        BigDecimal amount = price.multiply(new BigDecimal(num));
        if (amount.compareTo(user.getAmount()) > 0) {
            throw new RuntimeException("用户余额不足");
        }
        orderService.createOrder(user,item,num);
    }

}
